package com.biluo.mvs

import android.icu.text.DecimalFormat
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Divider
import androidx.compose.material.TextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import com.biluo.mvs.model.*
import com.biluo.mvs.network.PaymentApi
import com.biluo.mvs.network.TicketApi
import com.biluo.mvs.network.VehicleOwnerApi
import com.biluo.mvs.ui.theme.Purple40
import com.biluo.mvs.utils.GlobalData
import com.biluo.mvs.utils.Utils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.math.BigDecimal
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var ticketApi: TicketApi
    @Inject lateinit var userApi: VehicleOwnerApi
    @Inject lateinit var paymentApi: PaymentApi

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MaterialTheme {
                mainScreen()
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun mainScreen() {
        var title by remember { mutableStateOf("个人罚单") }
        var selectedItem by remember { mutableStateOf(1) }
        var ticket by remember { mutableStateOf(Ticket()) }

        LaunchedEffect(Unit) {
            // 获取用户信息
            Utils.handleResp(userApi.info(), "user") { user ->
                user as Map<*, *>
                GlobalData.user = VehicleOwner(
                    user["id"].toString(),
                    userId = user["userId"].toString(),
                    username = user["username"].toString(),
                )
            }
        }

        Scaffold(
            topBar = {  // 顶部导航栏
                TopAppBar(
                    title = { Text(text = title, style = MaterialTheme.typography.headlineMedium) },
                    actions = {
                        IconButton(onClick = {}) {
                            Icon(imageVector = Icons.Filled.Menu, contentDescription = "菜单")
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Purple40, // 导航栏背景颜色
                        titleContentColor = Color.White, // 标题颜色
                        actionIconContentColor = Color.White, // 图标颜色
                    )
                )
            },
            bottomBar = {   // 底部导航栏
                BottomNavigation(
                    backgroundColor = Color(0xFFE0E0E0)    // 设置底部导航栏背景颜色
                ) {
                    BottomNavigationItem(
                        icon = {
                            Icon(
                                imageVector = Icons.Filled.Home, contentDescription = "主页",
                                tint = if (selectedItem == 1) Color(0xFF1E92EE) else LocalContentColor.current    // 选中时图标变色
                            )
                        },
                        label = {
                            Text(
                                text = "个人罚单", fontSize = TextUnit(12F, TextUnitType.Sp),
                                color = if (selectedItem == 1) Color(0xFF1E92EE) else Color.Unspecified   // 选中时文字变色
                            )
                        },
                        selected = selectedItem == 1,
                        onClick = { title = "个人罚单".also { selectedItem = 1 } },
                        //modifier = Modifier.background(if (selectedItem == 1) Color(0xFF1E92EE) else Color(0xFFE0E0E0)) // 选中时背景变色
                        //selectedContentColor = , // 选中项的颜色
                        //unselectedContentColor = Color.Gray // 未选中项的颜色
                    )
                    BottomNavigationItem(
                        icon = {
                            Icon(
                                imageVector = Icons.Filled.Info, contentDescription = "缴费",
                                tint = if (selectedItem == 2) Color(0xFF1E92EE) else LocalContentColor.current    // 选中时图标变色
                            )
                        },
                        label = {
                            Text(
                                text = "缴费", fontSize = TextUnit(12F, TextUnitType.Sp),
                                color = if (selectedItem == 2) Color(0xFF1E92EE) else Color.Unspecified   // 选中时文字变色
                            )
                        },
                        selected = selectedItem == 2,
                        onClick = { title = "缴费".also { selectedItem = 2 } },
                    )
                    BottomNavigationItem(
                        icon = {
                            Icon(
                                imageVector = Icons.Filled.Settings, contentDescription = "缴费记录",
                                tint = if (selectedItem == 3) Color(0xFF1E92EE) else LocalContentColor.current    // 选中时图标变色
                            )
                        },
                        label = {
                            Text(
                                text = "缴费记录", fontSize = TextUnit(12F, TextUnitType.Sp),
                                color = if (selectedItem == 3) Color(0xFF1E92EE) else Color.Unspecified   // 选中时文字变色
                            )
                        },
                        selected = selectedItem == 3,
                        onClick = { title = "缴费记录".also { selectedItem = 3} },
                    )
                }
            }
        ) { innerPadding -> // 内容区域
            when (selectedItem) {
                1 -> { ticketListScreen(innerPadding, { ticket = it }, { selectedItem = it }) }

                2 -> { paymentScreen(innerPadding, ticket) }

                3 -> { paymentRecordScreen(innerPadding) }
            }
        }
    }

    @Composable
    fun ticketListScreen(innerPadding: PaddingValues, setTicket: (Ticket) -> Unit, setSelectedItem: (Int) -> Unit) {
        var ticketList by remember { mutableStateOf(listOf<Ticket>()) }

        suspend fun getTicketList() {
            // 获取数据
            Utils.handleResp(ticketApi.list(1, 100), "page") {
                var list = (it as Map<*, *>)["list"] as List<*>
                val data = list.map { item ->
                    item as Map<*, *>
                    Ticket(
                        item["id"].toString(),
                        BigDecimal(item["waitFine"].toString()),
                        BigDecimal(item["waitOverdueFee"].toString()),
                        BigDecimal(item["fineAmount"].toString()),
                        BigDecimal(item["overdueFee"].toString()),
                        (item["violationDay"] as Double).toInt(),
                        item["createTime"].toString()
                    )
                }
                ticketList = data
            }
        }

        // 在组件首次绘制后仅执行一次的副作用
        LaunchedEffect(Unit) { getTicketList() }

        Column(modifier = Modifier.padding(innerPadding).fillMaxSize()) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth().height(30.dp)
            )
            {
                Text(text = "编号", textAlign = TextAlign.Center, modifier = Modifier.weight(1.5F))
                Text(text = "待缴罚金", textAlign = TextAlign.Center, modifier = Modifier.weight(1F))
                Text(text = "待缴滞纳金", textAlign = TextAlign.Center, modifier = Modifier.weight(1F))
            }
            Divider(color = Color.Black, thickness = 0.8.dp)    // 分隔线
            LazyColumn {   // 可滑动列表
                items(ticketList) { item ->
                    Row(
                        horizontalArrangement = Arrangement.SpaceBetween,
                        modifier = Modifier.fillMaxWidth().clickable {
                            setSelectedItem(2).also { setTicket(item) }
                        }
                    ) {
                        Text(
                            text = item.id,
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            modifier = Modifier.weight(1.5F)
                        )
                        Text(
                            text = DecimalFormat("#,##0.00 元").format(item.waitFine),
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            overflow = TextOverflow.Ellipsis, maxLines = 1,
                            modifier = Modifier.weight(1F)
                        )
                        Text(
                            text = DecimalFormat("#,##0.00 元").format(item.waitOverdueFee),
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            overflow = TextOverflow.Ellipsis, maxLines = 1,
                            modifier = Modifier.weight(1F)
                        )
                    }
                    Divider()
                }
            }
        }
    }

    @Composable
    fun paymentScreen(innerPadding: PaddingValues, ticket: Ticket) {
        var id by remember { mutableStateOf(ticket.id) }
        var ticket by remember { mutableStateOf(ticket) }
        var dialogVisible by remember { mutableStateOf(false) }
        var moneyStr by remember { mutableStateOf("") }
        var scope = rememberCoroutineScope()

        Column(modifier = Modifier.padding(innerPadding).fillMaxSize()) {
            Row(Modifier.fillMaxWidth().padding(10.dp), verticalAlignment = Alignment.CenterVertically) {
                TextField(
                    value = id,
                    onValueChange = { id = it },
                    placeholder = { Text("请输入罚单编号") },
                    singleLine = true,
                    modifier = Modifier.weight(4F)
                )
                Button(
                    onClick = {
                        if (id.isEmpty()) {
                            Utils.showToast("请输入罚单编号")
                            return@Button
                        }
                        scope.launch {
                            Utils.handleResp(ticketApi.info(id), "ticket") { ticketData ->
                                if (ticketData == null) {
                                    Utils.showToast("该罚单不存在")
                                    return@handleResp
                                }
                                ticketData as Map<*, *>
                                ticket = Ticket(
                                    ticketData["id"].toString(),
                                    BigDecimal(ticketData["waitFine"].toString()),
                                    BigDecimal(ticketData["waitOverdueFee"].toString()),
                                    BigDecimal(ticketData["fineAmount"].toString()),
                                    BigDecimal(ticketData["overdueFee"].toString()),
                                    (ticketData["violationDay"] as Double).toInt(),
                                    ticketData["createTime"].toString()
                                )
                            }
                        }
                    },
                    shape = RoundedCornerShape(10.dp),
                    modifier = Modifier.weight(2F).padding(start = 10.dp)
                ) {
                    Text("查询")
                }
            }
            if (ticket.id.isNotEmpty()) {
                Column(modifier = Modifier.fillMaxWidth().padding(10.dp)) {
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(text = "编号：", modifier = Modifier.weight(1F))
                        Text(text = ticket.id, modifier = Modifier.weight(2F))
                    }
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(text = "待缴罚金：", modifier = Modifier.weight(1F))
                        Text(text = DecimalFormat("#,##0.00 元").format(ticket.waitFine), modifier = Modifier.weight(2F))
                    }
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(text = "待缴滞纳金：", modifier = Modifier.weight(1F))
                        Text(text = DecimalFormat("#,##0.00 元").format(ticket.waitOverdueFee), modifier = Modifier.weight(2F))
                    }
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(text = "违章时间：", modifier = Modifier.weight(1F))
                        Text(text = ticket.createTime, modifier = Modifier.weight(2F))
                    }
                    Row(modifier = Modifier.fillMaxWidth()) {
                        Text(text = "违章天数", modifier = Modifier.weight(1F))
                        Text(text = "${ticket.violationDay} 天", modifier = Modifier.weight(2F))
                    }
                }
                Button(
                    onClick = { dialogVisible = true },
                    shape = RoundedCornerShape(10.dp),
                    modifier = Modifier.fillMaxWidth().padding(10.dp),
                    enabled = ticket.waitFine > BigDecimal.ZERO || ticket.waitOverdueFee > BigDecimal.ZERO
                ) { Text("缴        费") }
            }
        }
        if (dialogVisible) {
            AlertDialog(
                title = {
                    Text(text = "缴费")
                },
                text = {
                    TextField(
                        value = moneyStr,
                        onValueChange = { moneyStr = it },
                        singleLine = true,
                        placeholder = { Text("请输入缴费金额（元）") }
                    )
                },
                onDismissRequest = {},
                confirmButton = {
                    TextButton(
                        onClick = {
                            if (moneyStr.isEmpty()) {
                                Utils.showToast("请输入缴费金额")
                                return@TextButton
                            }
                            if (!Regex("^\\d+(\\.\\d{1,2})?$").matches(moneyStr)) {
                                Utils.showToast("缴费金额为最多两位小数的正数")
                                return@TextButton
                            }
                            val money = moneyStr.toBigDecimal()
                            if (money > ticket.waitFine + ticket.waitOverdueFee) {
                                Utils.showToast("缴费金额不能大于待缴金额")
                                return@TextButton
                            }
                            scope.launch {
                                Utils.handleResp(ticketApi.payment(PaymentForm(money, ticket.id))) {
                                    Utils.showToast("缴费成功")
                                }
                            }
                            dialogVisible = false
                        }
                    ) { Text("确认") }
                },
                dismissButton = {
                    TextButton(
                        onClick = { dialogVisible = false }
                    ) { Text("取消") }
                }
            )
        }
    }

    @Composable
    fun paymentRecordScreen(innerPadding: PaddingValues) {
        var paymentList by remember { mutableStateOf(listOf<Payment>()) }

        LaunchedEffect(Unit) {
            Utils.handleResp(paymentApi.list(1, 100), "page") { page ->
                val list = (page as Map<*, *>)["list"] as List<*>
                paymentList = list.map {
                    val item = it as Map<*, *>
                    Payment(
                        item["id"].toString(),
                        BigDecimal(item["paymentMoney"].toString()),
                        item["paymentTime"].toString(),
                        item["username"].toString(),
                        (item["detailList"] as List<*>).map {
                            val detail = it as Map<*, *>
                            PaymentDetail(
                                detail["paymentId"].toString(),
                                detail["ticketId"].toString(),
                                BigDecimal(detail["paymentMoney"].toString()),
                                detail["createTime"].toString(),
                                detail["username"].toString()
                            )
                        }
                    )
                }
            }
        }

        Column(modifier = Modifier.padding(innerPadding).fillMaxSize()) {
            Row(
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxWidth().height(30.dp)
            )
            {
                Text(text = "缴费人", textAlign = TextAlign.Center, modifier = Modifier.weight(1F))
                Text(text = "缴费金额", textAlign = TextAlign.Center, modifier = Modifier.weight(1F))
                Text(text = "缴费时间", textAlign = TextAlign.Center, modifier = Modifier.weight(1.5F))
            }
            Divider(color = Color.Black, thickness = 0.8.dp)    // 分隔线
            LazyColumn {   // 可滑动列表
                items(paymentList) { item ->
                    Row(
                        horizontalArrangement = Arrangement.SpaceBetween,
                        modifier = Modifier.fillMaxWidth().clickable {}
                    ) {
                        Text(
                            text = item.username,
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            modifier = Modifier.weight(1F)
                        )
                        Text(
                            text = DecimalFormat("#,##0.00 元").format(item.paymentMoney),
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            overflow = TextOverflow.Ellipsis, maxLines = 1,
                            modifier = Modifier.weight(1F)
                        )
                        Text(
                            text = item.paymentTime,
                            textAlign = TextAlign.Center, fontSize = TextUnit(14F, TextUnitType.Sp),
                            overflow = TextOverflow.Ellipsis, maxLines = 1,
                            modifier = Modifier.weight(1.5F)
                        )
                    }
                    Divider()
                }
            }
        }
    }
}